"""
这是一个数据同步函数
用于实现：当Product中的表的数据发生变化时，
将变化同步到其他相关的表中
"""

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from workDjango import models
from workDjango.models import Product,ProductSales
from workDjango.utils import BootStrapModelForm
from django.shortcuts import render, redirect


# 定义信号处理函数
@receiver(post_save, sender=Product)
def update_sales_on_product_save(sender, instance, created, **kwargs):
    if created:
        # 处理新创建的产品
        ProductSales.objects.create(product=instance, quantity=1)
    else:
        # 处理更新的产品
        ProductSales.objects.filter(product=instance).update(product_name=instance.name)

@receiver(post_delete, sender=Product)
def update_sales_on_product_delete(sender, instance, **kwargs):
    # 处理删除的产品
    ProductSales.objects.filter(product=instance).delete()

# views.py 中的代码保持不变
class AddModelForm(BootStrapModelForm.AddModelForm):
    class Meta:
        model = models.Product
        fields = ["product_id", "category", "brand", "name", "price"]

def goods_add(request):
    if request.method == "GET":
        form = AddModelForm()
        return render(request, 'goods_add.html', {"add_form": form})
    form = AddModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/system/data_show')
    return render(request, 'goods_add.html', {"add_form": form})
